POJ-2456 Aggressive cows(贪心+二分 水题)

描述

传送门:POJ-2456 Aggressive cows

Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,…,xN (0 <= xi <= 1,000,000,000).

His C (2 <= C <= N) cows don’t like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?

输入描述

  • Line 1: Two space-separated integers: N and C

  • Lines 2..N+1: Line i+1 contains an integer stall location, xi

输出描述

  • Line 1: One integer: the largest minimum distance

示例

输入

1
2
3
4
5
6
5 3
1
2
8
4
9

输出

1
3

Hint

OUTPUT DETAILS:

FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.

Huge input data,scanf is recommended.

题解

题目大意

有n个牛栏,选m个放进牛,相当于一条线段上有 n 个点,选取 m 个点,使得相邻点之间的最小距离值最大。

思路

先排序,再二分枚举相邻两牛的间距,判断大于等于此间距下能否放进所有的牛。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define LL long long
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5 +10;
using namespace std;
int a[MAXN];
int n, c;

bool Judge(int m){
int last = 0;
for(int i = 1; i < c; i++){
int crt = last+1;
while(crt < n && a[crt] -a[last] < m){
crt++;
}
if(crt == n){
return false;
}
last = crt;
}
return true;
}

int main(){
scanf("%d%d", &n, &c);
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
sort(a, a+n);
int l = 0,r = INF;
while(1 < r-l){
int mid = (l+r)>>1;
if(Judge(mid)){
l = mid;
}
else{
r = mid;
}
}
printf("%d", l);
}